package cqu.edu.cn.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 注册拦截器，规定哪些请求会被拦截，哪些请求会被放行
 * 配置需要@Configuration注解
 * @author 杨鑫隆 and 高鸿成
 *
 */
@Configuration 
public class WebConfig implements WebMvcConfigurer {

    /*
     * 创建自定义的拦截器
     */
    @Bean
    WebInterceptor webInterceptor() {
        return new WebInterceptor();
    }

    /*
     * 添加拦截器，防止用户没有登录就直接访问app1的首页，但是用户直接从server端是被允许的
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.webInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/logOut");
    }


    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/"
    };

    /*
     * 处理对静态资源的访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }   
    }


}